package 代码随想录_补充题目.字符串反转系列;

/**
 * @author zx
 * @create 2023-02-08 22:59
 */
public class 反转字符串中的单词_151 {
    /**
     * @return 这样写自己可以想到,用到的都是自己掌握的东西
     * 和这题一样：剑指Offer58_翻转单词顺序
     */
    public String reverseWords2(String s) {
        StringBuilder temp = new StringBuilder(s);
        while(temp.length() > 0 && temp.charAt(0) == ' '){
            temp.deleteCharAt(0);
        }
        while(temp.length() > 0 && temp.charAt(temp.length() - 1) == ' '){
            temp.deleteCharAt(temp.length() - 1);
        }
        s = temp.toString();
        String res = "";
        String[] arr = s.split(" ");
        for(int i = arr.length - 1;i >= 0;i--){
            if(arr[i] != ""){
                String c = arr[i];
                res += c;
                if(i != 0){
                    res += " ";
                }
            }
        }
        //split(" ")方法不能分隔开连续空白符,所以这样不行
//        for(int i = arr.length - 1;i > 0;i--){
//            res = res + arr[i] + " ";
//        }
//        res += arr[0];
        return res;
    }

    /**
     * @return 这个方法感觉自己面试时写不出来
     */
    public String reverseWords(String s) {
        StringBuilder res = removeSpace(s);
        reverseString(res, 0, res.length() - 1);
        reverseEveryWord(res);
        return res.toString();
    }
    //移除多余空格
    private StringBuilder removeSpace(String s) {
        int left = 0, right = s.length() - 1;
        while(s.charAt(left) == ' ') {
            left++;
        }
        while(s.charAt(right) == ' ') {
            right--;
        }
        StringBuilder res = new StringBuilder();
        while(left <= right) {
            char c = s.charAt(left);
            if(c != ' ') {
                res.append(c);
            }else if (c == ' ' && res.charAt(res.length() - 1) != ' ') {
                res.append(c);
            }
            left++;
        }
        return res;
    }
    //字符串反转
    private void reverseString(StringBuilder sb, int left, int right){
        while(left < right){
            char temp = sb.charAt(left);
            sb.setCharAt(left,sb.charAt(right));
            sb.setCharAt(right,temp);
            left++;
            right--;
        }
    }
    //3.单词反转：   "eulb si yks eht" --> "blue is sky the"
    private void reverseEveryWord(StringBuilder sb){
        int left = 0,right = 0;
        while(left < sb.length()){
            while(right < sb.length() && sb.charAt(right) != ' '){
                right++;
            }
            reverseString(sb,left,right - 1);
            left = right + 1;
            right = right + 1;
        }
    }
}
